package com.ecube.test;

import com.alibaba.fastjson.JSON;
import com.ecube.mqtt.MqttUtils;
import com.ecube.mqtt.mysql.Query;
import com.ecube.protocol.ProtocolHelper;
import com.ecube.protocol.box.BoxInputAcbState;
import com.ecube.protocol.common.DataReportStandard;
import com.ecube.protocol.enums.BoxFunctionEnum;
import com.ecube.utils.EnumUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @author zhuweijun
 * @version 1.0.0
 * @since 2025/7/29 11:39
 */
public class SendBoxInputAcbState {

    public static void main(String[] args) throws Exception {
        while (true) {
            //sendRealDataMQTT("FAT", "TMS002025001", false);
            sendRealDataMQTT("FAT", "TMS002025005", false);
            //sendRealDataMQTT("FAT", "MSS00012", true);
            Thread.sleep(1000*10);
        }
    }

    public static void sendRealDataMQTT(String env, String deviceCode, boolean intervalFlag) {
        BoxInputAcbState inputAcbState = new BoxInputAcbState();
        BoxFunctionEnum function = (BoxFunctionEnum) EnumUtils.getFunction(inputAcbState.getClass());
        if(function == null){
            return;
        }

        String productCode = Query.getProductCode(env, deviceCode).split("/")[0];
        String pubTopic = productCode + "/" + deviceCode + "/" + function.getDirection() + "/" + function.getType();
        String version = Query.getVersion(env, deviceCode);

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        inputAcbState.setSwapId(null);
        inputAcbState.setInputAcbId("10-10-1");

        BigDecimal randomBigDecimal = new BigDecimal("180");
        if(intervalFlag){
            BigDecimal min = new BigDecimal("-300");
            BigDecimal max = new BigDecimal("560");
            int scale = 2; // 保留 2 位小数
            Random random = new Random();
            // 生成 [0.0, 1.0) 的 double
            double randomDouble = random.nextDouble();
            // 缩放到 [100.0, 200.0)
            randomBigDecimal = min.add(max.subtract(min).multiply(BigDecimal.valueOf(randomDouble)))
                    .setScale(scale, RoundingMode.HALF_UP);
        }

        // 低压进线有功功率
        inputAcbState.setInputActivePower(randomBigDecimal.floatValue());

        DataReportStandard reportStandard = new DataReportStandard();
        reportStandard.setHeader(ProtocolHelper.getReportHand(productCode, deviceCode, function.getFunction()));

        reportStandard.setDataBody(inputAcbState);

        String reportContent = JSON.toJSONString(reportStandard);
        System.out.println("发送报文内容：" + reportContent);
        MqttUtils.sendMQTT(env, pubTopic, reportContent);
        String time = dateFormat.format(date);
        MqttUtils.sendMQTT(env, productCode + "/" + deviceCode + "/S2M/keepalive", time);
    }
}
